package com.llw.notify.util;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

public class Utils {
    private static final String TAG = Utils.class.getSimpleName();

    /**
     * 通过 Context 获取 Activity 的名称
     *
     * @param context 与某个 Activity 对应的 Context
     * @return 成功则返回 Activity 名称，否则返回 null
     */
    public static String getActivityNameByContext(Context context) {
        try {
            while (context instanceof ContextWrapper) {
                if (context instanceof Activity) {
                    return ((Activity) context).getLocalClassName();
                }
                context = ((ContextWrapper) context).getBaseContext();
            }
        }
        catch (Exception e) {
            Log.e(TAG, "getActivityNameByContext: 获取Context<" + context + ">对应的 Activity 名称失败", e);
        }
        return null;
    }

    /**
     * 通过应用的包名获取应用的名称
     *
     * @param packageName 应用的包名
     * @return 成功：返回应用名称；失败：返回包名
     */
    public static String getAppNameByPackageName(final String packageName) {
        String appName = packageName;
        try {
            PackageManager packageManager = ContextHelper.application().getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            appName = packageManager.getApplicationLabel(applicationInfo).toString();
        } catch (Exception e) {
            Log.e(TAG, "getAppNameByPackageName: 获取包名<" + packageName + ">对应的应用名称失败", e);
        }

        return appName;
    }
}
